angular.module('start.user.auth.authrealname.ctrl', [])

  .controller('authrealnameCtrl', function($scope,$ionicActionSheet,$$cordovaImagePicker,$$cordovaCamera, $rootScope, $ionicPopup, $timeout, $location, $$UserAuthService, $$UploadImageService, $ionicLoading) {
    console.log("authrealnameCtrl");


    $scope.realnameData = {
      realName: "",
      idNO: "",
      idObversePic: "",
      idBackPic: "",
      sex: 0 // 性别 0男 1女
    };

    $scope.pageidObversePic = "img/zm.png";
    $scope.pageidBackPic = "img/bm.png";
    // $scope.realnameData = {
    //   realName: "猪八戒",
    //   idNO: "532621199306204016",
    //   idObversePic: "img/zm.png",
    //   idBackPic: "img/bm.png",
    //   sex: 0 // 性别 0男 1女
    // };




    // 提交实名认证表单
    $scope.submitAuthRealname = function() {
      if ($scope.validFormRealname()) {
        $ionicLoading.show({
          template: '上传中...'
        });
        // $scope.pageidObversePic = utils.base64_tx ;
        // $scope.pageidBackPic = utils.base64_tx;
        // var base64Arry = "" + utils.base64_tx + "," +  utils.base64_tx;
        var base64Arry = $scope.pageidObversePic + "," + $scope.pageidBackPic;
        // console.log(base64Arry);
        // 上传图片
        $$UploadImageService.uploadImage(base64Arry)
        .then(function(res) {

          if (res.errCode == 203) {
            console.log("图片上传成功");
            var imgArray = res.data.pic.split(",");
            $scope.realnameData.idObversePic = imgArray[0];
            $scope.realnameData.idBackPic = imgArray[1];
            // 提交表单数据
            $$UserAuthService.authRealname($scope.realnameData).then(function(res) {
              $ionicLoading.show({
                template: res.msg,
                noBackdrop: true,
                duration: 1500
              });
              // switch (res.errCode) {
              //   case 201:
              //     break;
              //   default:
              //     // statements_def
              //     break;
              // }
              $location.path("authselect");
            });
          } else {
            $ionicLoading.show({
              template: "图片上传失败 " + res.msg,
              noBackdrop: true,
              duration: 1500
            });
          }

        });

      } // if validForm
    };


    // 表单校验
    $scope.validFormRealname = function() {
      // return true;
      if (!checkText($scope.realnameData.realName)) {
        $scope.alertPopup("请正确输入姓名");
        return false;
      }
      if (!IdentityCodeValid($scope.realnameData.idNO)) {
        $scope.alertPopup("请正确输入身份证号");
        return false;
      }
      if ($scope.pageidObversePic === "img/zm.png") {
        $scope.alertPopup("请正确上传正面身份证");
        return false;
      }
      if ($scope.pageidBackPic === "img/bm.png") {
        $scope.alertPopup("请正确上传反面身份证");
        return false;
      }
      return true;
    };


    // 上传身份证正面按钮点击
    $scope.selectImgIdObversePic = function() {

      if ($rootScope.config.isWebView) { // cordova app端中
        $scope.appphoto_idobverse();
      } else { // 浏览器中
        $("#selectImgIdObversePicInput").trigger('click');
      }

    };

    // 上传身份证背面按钮点击
    $scope.selectImgIdBackPic = function() {

      if ($rootScope.config.isWebView) { // cordova app端中
        $scope.appphoto_idback();
      } else { // 浏览器中
        $("#selectImgIdBackPicInput").trigger('click');
      }

    };

    // 上传身份证正面input监听
    document.getElementById("selectImgIdObversePicInput").addEventListener('change', function() {
      console.log("selectImgIdObversePicInput--change");
      var file = this.files[0];
      //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
      if (!/image\/\w+/.test(file.type)) {
        $scope.alertPopup('请确保文件为图像类型');
        return false;
      } else {
        if (file.size > 2200000) {
          $ionicLoading.show({
            template: "请上传小于2M的图片",
            noBackdrop: true,
            duration: 1500
          });
          return;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          $scope.pageidObversePic = this.result;
          $scope.$apply();
        };
      }
    }, false);

    // app 选择图片 身份证正面
    $scope.appphoto_idobverse = function(argument) {
      // 选择上传方式
      var hideSheet_appphoto_idobverse = $ionicActionSheet.show({
        buttons: [
          { text: '相机拍照' },
          { text: '手机相册' }
        ],
        // destructiveText: 'Delete',
        titleText: '选择图片上传方式',
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          if (index == 0) {
            // 调用摄像头拍照
            var options = {
              quality: 50,
              destinationType: Camera.DestinationType.DATA_URL,
              sourceType: Camera.PictureSourceType.CAMERA,
              allowEdit: false,
              encodingType: Camera.EncodingType.JPEG,
              // targetWidth: 100,
              // targetHeight: 100,
              popoverOptions: CameraPopoverOptions,
              saveToPhotoAlbum: false,
              correctOrientation: true
            };
            $$cordovaCamera.getPicture(options).then(function(imageData) {
              $scope.pageidObversePic = "data:image/jpeg;base64," + imageData;
              hideSheet_appphoto_idobverse();
            }, function(err) {
              // error
            });
          } else if (index == 1) {
            // 调用手机相册
            $$cordovaImagePicker.getPictures({
                maximumImagesCount: 1,
                // width: 100,
                // height: 100,
                quality: 50
              })
              .then(function(results) {
                // console.log(results);
                var image = new Image();
                image.src = results[0];
                image.onload = function() {
                  var canvas = document.createElement("canvas");
                  canvas.width = this.width;
                  canvas.height = this.height;
                  var ctx = canvas.getContext("2d");
                  ctx.drawImage(this, 0, 0, this.width, this.height);
                  var ext = this.src.substring(this.src.lastIndexOf(".") + 1).toLowerCase();
                  var base64 = canvas.toDataURL("image/" + ext);
                  $scope.pageidObversePic = base64;
                  hideSheet_appphoto_idobverse();
                };
              }, function(error) {});
          }
        }
      });
    };



    // 上传身份证背面input监听
    document.getElementById("selectImgIdBackPicInput").addEventListener('change', function() {
      var file = this.files[0];
      //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
      if (!/image\/\w+/.test(file.type)) {
        $scope.alertPopup('请确保文件为图像类型');
        return false;
      } else {
        if (file.size > 2200000) {
          $ionicLoading.show({
            template: "请上传小于2M的图片",
            noBackdrop: true,
            duration: 1500
          });
          return;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          $scope.pageidBackPic = this.result;
          $scope.$apply();
        };
      }
    }, false);


    // app 选择图片 身份证背面
    $scope.appphoto_idback = function(argument) {
      // 选择上传方式
      var hideSheet_appphoto_idback = $ionicActionSheet.show({
        buttons: [
          { text: '   相机拍照' },
          { text: '   手机相册' }
        ],
        // destructiveText: 'Delete',
        titleText: '选择图片上传方式',
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          if (index == 0) {
            // 调用摄像头拍照
            var options = {
              quality: 50,
              destinationType: Camera.DestinationType.DATA_URL,
              sourceType: Camera.PictureSourceType.CAMERA,
              allowEdit: false,
              encodingType: Camera.EncodingType.JPEG,
              // targetWidth: 100,
              // targetHeight: 100,
              popoverOptions: CameraPopoverOptions,
              saveToPhotoAlbum: false,
              correctOrientation: true
            };
            $$cordovaCamera.getPicture(options).then(function(imageData) {
              hideSheet_appphoto_idback();
              $scope.pageidBackPic = "data:image/jpeg;base64," + imageData;
            }, function(err) {
              // error
            });
          } else if (index == 1) {
            // 调用手机相册
            var options = {
              maximumImagesCount: 1,
              // width: 100,
              // height: 100,
              quality: 50
            };
            $$cordovaImagePicker.getPictures(options)
              .then(function(results) {
                // console.log(results);
                var image = new Image();
                image.src = results[0];
                image.onload = function() {
                  var canvas = document.createElement("canvas");
                  canvas.width = this.width;
                  canvas.height = this.height;
                  var ctx = canvas.getContext("2d");
                  ctx.drawImage(this, 0, 0, this.width, this.height);
                  var ext = this.src.substring(this.src.lastIndexOf(".") + 1).toLowerCase();
                  var base64 = canvas.toDataURL("image/" + ext);
                  hideSheet_appphoto_idback();
                  $scope.pageidBackPic = base64;
                };
              }, function(error) {});
          }
        }
      });
    };


    $scope.removeLifePic = function(removeLifePicIndex) {
      var confirmPopup = $ionicPopup.confirm({
        title: '删除图片',
        template: '是否删除该图片',
        buttons: [
          { text: '取消' },
          {
            text: '<b>确定</b>',
            type: 'button-assertive',
            onTap: function(e) {
              $scope.gLifePicUrls.splice(removeLifePicIndex, 1); //清空数组
            }
          },
        ]
      });
    };


    $scope.alertPopup = function(title) {
      $ionicPopup.alert({
        title: title,
        okText: '确定', // String (默认: 'OK')。OK按钮的文字。
        okType: 'button-calm', // String (默认: 'button-positive')。OK按钮的类型。
      }).then(function(res) {
        console.log('确定提示框');
      });
    };

  });
